<template>
  <el-drawer
    v-model="drawerVisible"
    class="verify-report-drawer"
    :title="title"
    :size="size"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <template #title>
      <div class="flex justify-between mr-2">
        <div class="text-black font-bold flex items-center">
          <div>{{ title }}</div>
          <div class="text-gray-500 text-sm ml-2">{{ reportId }}</div>
        </div>

        <!-- <LangSwitch :model-value="currentLang" @change="handleLanguageChange" /> -->
      </div>
    </template>

    <div class="drawer-content">
      <div class="content-wrapper">
        <!-- 报告文件列表 -->
        <div
          v-for="reportItem in reportData"
          :key="reportItem.reportId"
          class="report-section mb-6"
        >
          <!-- 文件标题 -->
          <div class="file-header">
            <div class="file-title">
              <el-icon class="mr-2"><DocumentIconComponent /></el-icon>
              {{ reportItem.fileName }}
            </div>
            <div class="page-count">
              共 {{ reportItem.pages?.length || 0 }} 页
            </div>
          </div>

          <!-- 页面内容列表 -->
          <div class="pages-container">
            <div
              v-for="(page, index) in reportItem.pages"
              :key="page.id"
              class="page-item"
            >
              <!-- 页面标题 -->
              <div class="page-header">
                <span class="page-number">第 {{ index + 1 }} 页</span>
                <el-tag
                  v-if="page.hasMedicalImaging"
                  type="success"
                  size="small"
                >
                  包含影像资料
                </el-tag>
              </div>

              <!-- 页面内容：图片 + 编辑器 -->
              <div class="page-content">
                <!-- 左侧图片预览 -->
                <div class="image-preview">
                  <div class="image-container">
                    <el-image
                      :src="page.pageUrl"
                      :alt="`第${index + 1}页`"
                      fit="contain"
                      :preview-src-list="[page.pageUrl]"
                      class="page-image"
                      loading="lazy"
                    >
                      <template #error>
                        <div class="image-error">
                          <el-icon size="48"><PictureIcon /></el-icon>
                          <p>图片加载失败</p>
                        </div>
                      </template>
                    </el-image>
                  </div>
                </div>

                <!-- 右侧内容编辑 -->
                <div class="content-editor">
                  <div class="editor-header">
                    <span class="editor-label">内容校验</span>
                    <el-tooltip content="支持 Markdown 语法编辑">
                      <el-icon class="help-icon"
                        ><QuestionFilledIcon
                      /></el-icon>
                    </el-tooltip>
                  </div>

                  <div class="editor-wrapper">
                    <MdEditor
                      :id="`editor-${page.id}`"
                      :ref="setMdEditorRef(`mdEditor-${page.id}`)"
                      :content="page.content || ''"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="!reportData?.length" class="empty-state">
          <el-empty :image-size="120" description="暂无报告数据" />
        </div>
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <template #footer>
      <div class="drawer-footer">
        <el-button @click="handleSave(1)">保存草稿</el-button>
        <el-button type="primary" @click="handleSave(2)">提交</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { reportApi, ReportContentCalibrationVO } from "@/api/report-api";
import { ElMessage } from "element-plus";
import { defineEmits, defineExpose, defineProps, onMounted, ref } from "vue";

import MdEditor from "@/components/md/index.vue";
import {
  Document as DocumentIcon,
  Picture,
  QuestionFilled
} from "@element-plus/icons-vue";

// 注册图标组件
const DocumentIconComponent = DocumentIcon;
const PictureIcon = Picture;
const QuestionFilledIcon = QuestionFilled;

// 定义属性
const props = defineProps({
  title: {
    type: String,
    default: "报告校验"
  },
  size: {
    type: String,
    default: "90%"
  }
});

const reportId = ref<number>();

// 定义事件
const emit = defineEmits(["update:modelValue", "save", "submit", "close"]);

// 基础状态管理
const drawerVisible = ref(false);
const documentUrl = ref("");
const currentLang = ref("zh-CN");
const loading = ref(false);

// 管理MD编辑器的ref
const mdEditorRefs = ref<Record<string, InstanceType<typeof MdEditor>>>({});

// 设置动态ref的函数
const setMdEditorRef = (id: string) => {
  return (el: any) => {
    if (el) {
      mdEditorRefs.value[id] = el;
    }
  };
};

// 报告数据
const reportData = ref<ReportContentCalibrationVO[]>([]);

/**
 * 语言切换处理
 * @param lang 目标语言
 */
const handleLanguageChange = (lang: string) => {
  console.log("报告校验 - 语言切换为:", lang);
  currentLang.value = lang;
  // 重新加载数据以支持多语言
  loadReportData();
};

/**
 * 加载报告校验数据
 */
const loadReportData = async () => {
  console.log("reportId", reportId.value);
  if (!reportId.value) return;

  loading.value = true;
  console.log(`报告校验 - 开始加载报告数据, reportId: ${reportId.value}`);

  try {
    const res = await reportApi.reportPageAnalysis({
      reportId: reportId.value
    });
    console.log("报告校验 - API响应:", res);

    reportData.value = res.data || [];
  } catch (error) {
    console.error("报告校验 - 加载数据失败:", error);
    ElMessage.error("加载报告数据失败");
  } finally {
    loading.value = false;
  }
};

/**
 * 保存处理
 * @param type 保存类型：1-保存草稿，2-提交
 */
const handleSave = async (type: number) => {
  const actionName = type === 1 ? "保存草稿" : "提交";
  console.log(`报告校验 - ${actionName}开始`);

  loading.value = true;

  const items = [];

  for (const item of reportData.value) {
    if (item.pages && Array.isArray(item.pages)) {
      for (const v of item.pages) {
        const refKey = `mdEditor-${v.id}`;
        const mdEditor = mdEditorRefs.value[refKey];

        console.log(`报告校验 - 获取编辑器内容: ${refKey}`, mdEditor);

        let content = v.content || ""; // 默认使用原始内容

        if (mdEditor && typeof mdEditor.getContent === "function") {
          try {
            const editorContent = mdEditor.getContent();
            if (editorContent && editorContent.trim()) {
              content = editorContent;
              console.log(
                `报告校验 - 获取Markdown内容成功: ${refKey}`,
                content
              );
            } else {
              console.log(`报告校验 - 编辑器内容为空，使用原始内容: ${refKey}`);
            }
          } catch (error) {
            console.error(`报告校验 - 获取编辑器内容失败: ${refKey}`, error);
          }
        } else {
          console.warn(
            `报告校验 - 编辑器引用无效或getContent方法不存在: ${refKey}`,
            {
              mdEditor,
              hasGetContent:
                mdEditor && typeof mdEditor.getContent === "function"
            }
          );
        }

        items.push({
          id: v.id,
          content: content,
          rawContent: v.content
        });
      }
    }
  }

  try {
    if (items.length === 0) {
      ElMessage.warning("没有需要保存的内容");
      return;
    }

    const saveData = await reportApi.reportPageAnalysisBatchEdit({
      reportId: reportId.value,
      items,
      readyToPublish: type === 2 // type === 1 时为 false (保存草稿), type === 2 时为 true (发布)
    });

    ElMessage.success(`${actionName}成功`);
    emit("save", { type, data: saveData, itemsCount: items.length });

    console.log(`报告校验 - ${actionName}完成:`, {
      type,
      itemsCount: items.length,
      response: saveData
    });

    // 只有提交时才关闭抽屉
    if (type === 2) {
      closeDrawer();
    }
  } catch (error) {
    console.error(`报告校验 - ${actionName}失败:`, error);
    ElMessage.error(`${actionName}失败，请重试`);
  } finally {
    loading.value = false;
  }
};

/**
 * 关闭抽屉
 */
const closeDrawer = () => {
  console.log("报告校验 - 关闭抽屉");
  drawerVisible.value = false;
  emit("update:modelValue", false);
  // 触发关闭事件，通知外部组件刷新列表
  emit("close");
  reportData.value = [];

  // 清理MD编辑器refs
  mdEditorRefs.value = {};
  console.log("报告校验 - 已清理编辑器引用");
};

// 对外暴露的方法
defineExpose({
  /**
   * 打开抽屉的方法
   * @param id 报告ID
   * @param documentUrlParam 文档URL
   */
  open(id: number, documentUrlParam?: string) {
    console.log("报告校验 - 打开抽屉, reportId:", id);
    reportId.value = id;

    drawerVisible.value = true;
    documentUrl.value = documentUrlParam || "";

    // 加载初始数据
    loadReportData();
  },

  /**
   * 获取当前编辑器refs（开发调试用）
   */
  getEditorRefs() {
    return mdEditorRefs.value;
  },

  /**
   * 手动触发保存（开发调试用）
   */
  forceSave(type = 1) {
    return handleSave(type);
  }
});

onMounted(() => {
  if (reportId.value) {
    loadReportData();
  }
});
</script>

<style lang="scss">
.verify-report-drawer {
  .el-drawer__header {
    padding: 20px 24px !important;
    border-bottom: 1px solid #f0f0f0 !important;
    margin-bottom: 0 !important;
    background-color: #fff !important;
  }

  .el-drawer__title {
    font-size: 16px !important;
    font-weight: 600 !important;
    color: #333 !important;
  }

  .el-drawer__body {
    padding: 0 !important;
    display: flex;
    flex-direction: column;
    height: 100%;
  }
}

.drawer-content {
  padding: 0;
  height: 100%;
  overflow: hidden;

  .content-wrapper {
    height: 100%;
    overflow-y: auto;
    padding: 20px;
  }
}

// 报告部分样式
.report-section {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

// 文件标题样式
.file-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;

  .file-title {
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: 600;

    .el-icon {
      color: rgba(255, 255, 255, 0.9);
    }
  }

  .page-count {
    font-size: 14px;
    opacity: 0.9;
  }
}

// 页面容器样式
.pages-container {
  padding: 0;
}

// 页面项样式
.page-item {
  border-bottom: 1px solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }
}

// 页面标题样式
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;

  .page-number {
    font-weight: 500;
    color: #333;
  }
}

// 页面内容样式
.page-content {
  display: flex;
  min-height: 400px;
}

// 图片预览样式
.image-preview {
  width: 50%;
  border-right: 1px solid #f0f0f0;
  background: #f8f9fa;
  position: relative;

  .image-container {
    height: 100%;
    display: flex;
    align-items: flex-start;
    justify-content: center;
    padding: 20px;
  }

  .page-image {
    max-width: 100%;
    max-height: 100%;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);

    :deep(.el-image__inner) {
      border-radius: 8px;
    }
  }

  .image-error {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 200px;
    color: #909399;

    p {
      margin-top: 12px;
      font-size: 14px;
    }
  }
}

// 内容编辑器样式
.content-editor {
  width: 50%;
  display: flex;
  flex-direction: column;
  background: #fff;

  .editor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    background: #f8f9fa;
    border-bottom: 1px solid #ebeef5;

    .editor-label {
      font-weight: 500;
      color: #333;
      font-size: 14px;
    }

    .help-icon {
      color: #909399;
      cursor: help;

      &:hover {
        color: #409eff;
      }
    }
  }

  .editor-wrapper {
    flex: 1;
    padding: 16px;

    :deep(.w-full) {
      height: 100%;
    }

    :deep(.ProseMirror) {
      min-height: 300px;
      max-height: 400px;
      padding: 12px;
      border: 1px solid #dcdfe6;
      border-radius: 6px;
      font-size: 14px;
      line-height: 1.6;

      &:focus {
        outline: none;
        border-color: #409eff;
        box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
      }
    }

    :deep(.menubar) {
      margin-bottom: 8px;
      padding: 8px 12px;
      background: #f8f9fa;
      border: 1px solid #dcdfe6;
      border-bottom: none;
      border-radius: 6px 6px 0 0;

      .menuicon {
        display: inline-block;
        padding: 4px 8px;
        margin-right: 4px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        color: #606266;
        transition: all 0.2s;

        &:hover {
          background: #e6f7ff;
          color: #409eff;
        }

        &:last-child {
          margin-right: 0;
        }
      }
    }
  }
}

// 空状态样式
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

// 响应式设计
@media (max-width: 1200px) {
  .page-content {
    .image-preview {
      width: 45%;
    }

    .content-editor {
      width: 55%;
    }
  }
}

@media (max-width: 768px) {
  .drawer-content {
    .content-wrapper {
      padding: 12px;
    }
  }

  .page-content {
    flex-direction: column;

    .image-preview,
    .content-editor {
      width: 100%;
    }

    .image-preview {
      border-right: none;
      border-bottom: 1px solid #f0f0f0;
      min-height: 250px;
    }

    .content-editor {
      .editor-wrapper {
        :deep(.ProseMirror) {
          min-height: 200px;
          max-height: 300px;
        }
      }
    }
  }

  .file-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}

.drawer-footer {
  padding: 16px 20px;
  border-top: 1px solid #f0f0f0;
  background-color: #fff;
  text-align: right;

  .el-button {
    margin-left: 12px;

    &:first-child {
      margin-left: 0;
    }
  }
}
</style>
